package com.monochromebytes.mononet.test.network;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;

import com.monochromebytes.mononet.stub.Serializer;
import com.monochromebytes.mononet.stub.Stub;
import com.monochromebytes.mononet.virtual.DataPacket;

public class SimpleSerializer implements Serializer {

    @Override
    public Object deserialize(ByteBuffer data, Stub stub) {
        try {
            byte[] array = new byte[data.remaining()];
            data.get(array, 0, array.length);

            ByteArrayInputStream bais = new ByteArrayInputStream(array);
            ObjectInputStream ois = new ObjectInputStream(bais);
            Object object = ois.readObject();
            ois.close();

            return object;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public ByteBuffer serialize(Object object, Stub stub) throws IOException {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream(DataPacket.MAX_LENGTH);
        ObjectOutputStream objectStream = new ObjectOutputStream(byteStream);
        objectStream.writeObject(object);

        byte[] bytes = byteStream.toByteArray();
        ByteBuffer data = ByteBuffer.allocate(bytes.length);
        data.put(bytes);
        data.flip();
        objectStream.close();

        return data;
    }
}
